package com.example.video.util.queue;

import com.example.video.entity.Account;
import com.example.video.service.impl.AccountServiceImpl;
import com.example.video.service.impl.VideoServiceImpl;
import com.example.video.thread.ResThread;
import com.example.video.util.HHdata;
import com.example.video.util.download.DownTask;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.util.concurrent.*;

/**
 * 下载任务队列
 */
@Component
@Slf4j
public class DownQueueManager {

    @Resource
    private HHdata hHdata;
    @Resource
    private AccountServiceImpl accountService;
    @Resource
    private VideoServiceImpl videoService;
    @Resource
    private DownTask downloader;

    // 阻塞队列，生产者put，消费者take，无需手动加锁
    private final BlockingQueue<ResThread> taskQueue;
    // 线程池，用来管理线程执行
    private final ExecutorService executor;
//    private final int maxQueueSize;


    /**
     * 初始化任务队列、线程池
     */
    public DownQueueManager() {
        // Linked这个实现类无界的
        taskQueue = new LinkedBlockingQueue<>();
        executor = Executors.newFixedThreadPool(2);
        log.info("初始化任务队列、线程池；");
    }

    /**
     * 添加任务
     */
    public boolean addTask(Account account, String nextCursor)  {
        boolean flag =false;
        ResThread task = new ResThread(hHdata, account, nextCursor, downloader);
        try {
            log.info("downLoadTask -> addTask -> msg: 入栈操作");
            taskQueue.put(task);
            flag = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * spring初始化时执行
     */
    @PostConstruct
    public void initialize() {
        log.info("DownQueueManager -> init -> msg: VideoDownloader start");
        start();
    }

    /**
     * 开始执行
     */
    public void start() {
        executor.execute(() -> {
            while (true) {
                try {
                    ResThread task = taskQueue.take();
                    executor.execute(task);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
    }



}
